// 考试管理数据存储
import { generateMockPapers, generateMockExams, generateMockSubmissions } from './examMockData';

// 试卷模板接口
export interface ExamTemplate {
  id: string;
  name: string;
  description: string;
  totalScore: number;
  duration: number; // 分钟
  difficulty: "简单" | "中等" | "困难";
  questionTypes: {
    choice: number; // 选择题数量
    programming: number; // 编程题数量
    analysis: number; // 分析题数量
    fill: number; // 填空题数量
    essay: number; // 简答题数量
  };
  subject: string; // 学科
  tags: string[];
  createTime: string;
  updateTime: string;
  usageCount: number;
  isDefault: boolean;
  creator: string;
  // 新增字段
  aiDescription?: string; // AI生成辅助描述
  questionRequirements?: {
    choice?: string;
    programming?: string;
    analysis?: string;
    fill?: string;
    essay?: string;
  };
  scoringRules?: {
    choice: number;
    programming: number;
    analysis: number;
    fill: number;
    essay: number;
  };
}

// 生成的试卷接口
export interface GeneratedPaper {
  id: string;
  templateId: string;
  templateName: string;
  name: string;
  questions?: GeneratedQuestion[];
  totalScore: number;
  duration: number;
  createTime: string;
  status: "generating" | "completed" | "failed";
  generationProgress: number;
}

// 生成的题目接口
export interface GeneratedQuestion {
  id: string;
  type: "choice" | "programming" | "analysis" | "fill" | "essay";
  content: string;
  answer: string;
  score: number;
  options?: string[];
  analysis?: string;
  difficulty: "简单" | "中等" | "困难";
  knowledge: string[];
  tags: string[];
  canRegenerate: boolean;
}

// 试卷接口
export interface ExamPaper {
  id: string;
  name: string;
  code: string;
  courseId: string;
  courseName: string;
  totalScore: number;
  duration: number; // 分钟
  questionCount: number;
  difficulty: "简单" | "中等" | "困难";
  status: "draft" | "published" | "archived";
  createTime: string;
  updateTime: string;
  creator: string;
  description?: string;
  tags: string[];
  isTemplate: boolean;
  usageCount: number;
  averageScore?: number;
  passRate?: number;
  questions?: any[]; // 题目详情
}

// 考试接口
export interface Exam {
  id: string;
  name: string;
  paperId: string;
  paperName: string;
  courseId: string;
  courseName: string;
  startTime: string;
  endTime: string;
  duration: number; // 分钟
  status: "draft" | "published" | "ongoing" | "ended" | "graded";
  totalStudents: number;
  submittedCount: number;
  gradedCount: number;
  averageScore?: number;
  passRate?: number;
  createTime: string;
  publishTime?: string;
  selectedClasses: string[]; // 选中的班级ID
  selectedCourses: string[]; // 选中的课程ID
  settings: {
    allowLateSubmission: boolean;
    maxLateMinutes: number;
    allowReview: boolean;
    autoGrade: boolean;
    requireProctor: boolean;
  };
}

// 考试提交接口
export interface ExamSubmission {
  id: string;
  examId: string;
  examName: string;
  studentId: string;
  studentName: string;
  className: string;
  submitTime: string;
  status: "submitted" | "graded" | "published" | "late";
  score?: number;
  totalScore: number;
  timeSpent: number; // 分钟
  gradedBy?: string;
  gradedTime?: string;
  comments?: string;
  aiScore?: number;
  aiComments?: string;
  teacherScore?: number;
  teacherComments?: string;
}

// 全局状态管理
class ExamStore {
  private papers: ExamPaper[] = [];
  private exams: Exam[] = [];
  private submissions: ExamSubmission[] = [];
  private templates: ExamTemplate[] = [];
  private generatedPapers: GeneratedPaper[] = [];

  constructor() {
    this.loadInitialData();
  }

  // 加载初始数据
  private loadInitialData() {
    this.papers = generateMockPapers();
    this.exams = generateMockExams();
    this.submissions = generateMockSubmissions();
    this.loadMockTemplates();
  }

  // 加载模拟模板数据
  private loadMockTemplates() {
    this.templates = [
      {
        id: "t1",
        name: "JavaScript基础测试",
        description: "涵盖JavaScript基础语法、数据类型、函数、对象等核心概念",
        totalScore: 100,
        duration: 90,
        difficulty: "中等",
        questionTypes: {
          choice: 10,
          programming: 3,
          analysis: 2,
          fill: 5,
          essay: 2,
        },
        subject: "前端开发",
        tags: ["JavaScript", "基础语法", "前端"],
        createTime: "2024-01-15 10:00:00",
        updateTime: "2024-01-15 10:00:00",
        usageCount: 15,
        isDefault: false,
        creator: "张教授",
        aiDescription: "重点考察JavaScript的基础语法和核心概念，题目应该贴近实际开发场景",
        questionRequirements: {
          choice: "考察基础语法知识点，选项要清晰明确",
          programming: "要求编写简单的JavaScript函数或代码片段",
          analysis: "分析代码执行结果或逻辑错误",
          fill: "填写关键语法或概念",
          essay: "解释JavaScript概念或编程思路"
        },
        scoringRules: {
          choice: 4,
          programming: 15,
          analysis: 10,
          fill: 3,
          essay: 8
        }
      },
      {
        id: "t2",
        name: "React框架测试",
        description: "React组件、状态管理、生命周期、Hooks等核心知识点",
        totalScore: 100,
        duration: 120,
        difficulty: "困难",
        questionTypes: {
          choice: 8,
          programming: 4,
          analysis: 2,
          fill: 3,
          essay: 3,
        },
        subject: "前端开发",
        tags: ["React", "组件", "状态管理"],
        createTime: "2024-01-10 14:30:00",
        updateTime: "2024-01-12 16:20:00",
        usageCount: 8,
        isDefault: false,
        creator: "李副教授",
        aiDescription: "深入考察React框架的核心概念和实际应用能力",
        questionRequirements: {
          choice: "考察React核心概念和API使用",
          programming: "编写React组件或使用Hooks",
          analysis: "分析组件渲染或状态变化",
          fill: "填写React相关概念或API",
          essay: "解释React设计理念或最佳实践"
        },
        scoringRules: {
          choice: 4,
          programming: 15,
          analysis: 10,
          fill: 3,
          essay: 8
        }
      },
      {
        id: "t3",
        name: "数据结构与算法",
        description: "线性表、栈、队列、树、图等基本数据结构及算法",
        totalScore: 100,
        duration: 150,
        difficulty: "困难",
        questionTypes: {
          choice: 15,
          programming: 5,
          analysis: 2,
          fill: 3,
          essay: 1,
        },
        subject: "计算机科学",
        tags: ["数据结构", "算法", "编程"],
        createTime: "2024-01-05 09:15:00",
        updateTime: "2024-01-08 11:45:00",
        usageCount: 25,
        isDefault: true,
        creator: "王讲师",
        aiDescription: "全面考察数据结构和算法的理论基础与编程实现能力",
        questionRequirements: {
          choice: "考察数据结构概念和算法复杂度",
          programming: "实现基本数据结构或算法",
          analysis: "分析算法复杂度或数据结构操作",
          fill: "填写算法步骤或数据结构特性",
          essay: "解释算法设计思路或数据结构选择"
        },
        scoringRules: {
          choice: 4,
          programming: 15,
          analysis: 10,
          fill: 3,
          essay: 8
        }
      },
      {
        id: "t4",
        name: "Java程序设计基础",
        description: "Java语言基础、面向对象编程、异常处理、集合框架等",
        totalScore: 100,
        duration: 120,
        difficulty: "中等",
        questionTypes: {
          choice: 12,
          programming: 4,
          analysis: 2,
          fill: 4,
          essay: 2,
        },
        subject: "后端开发",
        tags: ["Java", "面向对象", "编程基础"],
        createTime: "2024-01-20 09:00:00",
        updateTime: "2024-01-20 09:00:00",
        usageCount: 12,
        isDefault: false,
        creator: "张教授",
      },
      {
        id: "t5",
        name: "数据库原理与应用",
        description: "SQL语言、数据库设计、事务处理、索引优化等",
        totalScore: 100,
        duration: 100,
        difficulty: "中等",
        questionTypes: {
          choice: 10,
          programming: 2,
          analysis: 3,
          fill: 6,
          essay: 2,
        },
        subject: "数据库",
        tags: ["SQL", "数据库设计", "事务"],
        createTime: "2024-01-18 14:30:00",
        updateTime: "2024-01-18 14:30:00",
        usageCount: 18,
        isDefault: false,
        creator: "陈教授",
      },
      {
        id: "t6",
        name: "软件工程概论",
        description: "软件开发流程、需求分析、设计模式、测试方法等",
        totalScore: 100,
        duration: 90,
        difficulty: "简单",
        questionTypes: {
          choice: 15,
          programming: 1,
          analysis: 4,
          fill: 3,
          essay: 3,
        },
        subject: "软件工程",
        tags: ["软件工程", "开发流程", "设计模式"],
        createTime: "2024-01-22 11:00:00",
        updateTime: "2024-01-22 11:00:00",
        usageCount: 6,
        isDefault: false,
        creator: "刘副教授",
      },
    ];
  }

  // 获取所有试卷
  getPapers(): ExamPaper[] {
    return this.papers;
  }

  // 获取所有考试
  getExams(): Exam[] {
    return this.exams;
  }

  // 获取所有提交
  getSubmissions(): ExamSubmission[] {
    return this.submissions;
  }

  // 获取所有模板
  getTemplates(): ExamTemplate[] {
    return this.templates;
  }

  // 获取所有生成的试卷
  getGeneratedPapers(): GeneratedPaper[] {
    return this.generatedPapers;
  }

  // 添加新试卷
  addPaper(paper: Omit<ExamPaper, 'id' | 'createTime' | 'updateTime' | 'status' | 'usageCount' | 'isTemplate'>) {
    // 生成唯一ID
    const newPaper: ExamPaper = {
      ...paper,
      id: `p${Date.now()}`,
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
      status: "draft" as const,
      usageCount: 0,
      isTemplate: false,
    };
    this.papers.push(newPaper);
    return newPaper;
  }

  // 更新试卷
  updatePaper(paperId: string, updates: Partial<ExamPaper>) {
    const index = this.papers.findIndex(p => p.id === paperId);
    if (index !== -1) {
      this.papers[index] = {
        ...this.papers[index],
        ...updates,
        updateTime: new Date().toISOString(),
      };
      return this.papers[index];
    }
    return null;
  }

  // 删除试卷
  deletePaper(paperId: string) {
    const index = this.papers.findIndex(p => p.id === paperId);
    if (index !== -1) {
      this.papers.splice(index, 1);
      return true;
    }
    return false;
  }

  // 添加新考试
  addExam(exam: Omit<Exam, 'id' | 'createTime' | 'status' | 'submittedCount' | 'gradedCount'>) {
    const newExam: Exam = {
      ...exam,
      id: `e${Date.now()}`,
      createTime: new Date().toISOString(),
      status: "draft" as const,
      submittedCount: 0,
      gradedCount: 0,
    };
    this.exams.push(newExam);
    return newExam;
  }

  // 发布考试
  publishExam(examId: string) {
    const exam = this.exams.find(e => e.id === examId);
    if (exam) {
      exam.status = "published";
      exam.publishTime = new Date().toISOString();
      return exam;
    }
    return null;
  }

  // 更新考试
  updateExam(examId: string, updates: Partial<Exam>) {
    const index = this.exams.findIndex(e => e.id === examId);
    if (index !== -1) {
      this.exams[index] = {
        ...this.exams[index],
        ...updates,
      };
      return this.exams[index];
    }
    return null;
  }

  // 删除考试
  deleteExam(examId: string) {
    const index = this.exams.findIndex(e => e.id === examId);
    if (index !== -1) {
      this.exams.splice(index, 1);
      return true;
    }
    return false;
  }

  // 添加考试提交
  addSubmission(submission: Omit<ExamSubmission, 'id'>) {
    const newSubmission: ExamSubmission = {
      ...submission,
      id: `s${Date.now()}`,
    };
    this.submissions.push(newSubmission);
    return newSubmission;
  }

  // 更新提交
  updateSubmission(submissionId: string, updates: Partial<ExamSubmission>) {
    const index = this.submissions.findIndex(s => s.id === submissionId);
    if (index !== -1) {
      this.submissions[index] = {
        ...this.submissions[index],
        ...updates,
      };
      return this.submissions[index];
    }
    return null;
  }

  // 获取统计数据
  getStatistics() {
    return {
      totalPapers: this.papers.length,
      publishedPapers: this.papers.filter(p => p.status === "published").length,
      totalExams: this.exams.length,
      ongoingExams: this.exams.filter(e => e.status === "ongoing").length,
      totalSubmissions: this.submissions.length,
      gradedSubmissions: this.submissions.filter(s => s.status === "graded").length,
      averageScore: this.submissions.filter(s => s.score).reduce((sum, s) => sum + (s.score || 0), 0) / this.submissions.filter(s => s.score).length,
    };
  }

  // 根据ID获取试卷
  getPaperById(paperId: string): ExamPaper | undefined {
    return this.papers.find(p => p.id === paperId);
  }

  // 根据ID获取考试
  getExamById(examId: string): Exam | undefined {
    return this.exams.find(e => e.id === examId);
  }

  // 根据考试ID获取提交
  getSubmissionsByExamId(examId: string): ExamSubmission[] {
    return this.submissions.filter(s => s.examId === examId);
  }

  // 添加新模板
  addTemplate(template: Omit<ExamTemplate, 'id' | 'createTime' | 'updateTime' | 'usageCount'>) {
    const newTemplate: ExamTemplate = {
      ...template,
      id: `t${Date.now()}`,
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
      usageCount: 0,
    };
    this.templates.push(newTemplate);
    return newTemplate;
  }

  // 更新模板
  updateTemplate(templateId: string, updates: Partial<ExamTemplate>) {
    const index = this.templates.findIndex(t => t.id === templateId);
    if (index !== -1) {
      this.templates[index] = {
        ...this.templates[index],
        ...updates,
        updateTime: new Date().toISOString(),
      };
      return this.templates[index];
    }
    return null;
  }

  // 删除模板
  deleteTemplate(templateId: string) {
    const index = this.templates.findIndex(t => t.id === templateId);
    if (index !== -1) {
      this.templates.splice(index, 1);
      return true;
    }
    return false;
  }

  // 根据ID获取模板
  getTemplateById(templateId: string): ExamTemplate | undefined {
    return this.templates.find(t => t.id === templateId);
  }

  // 增加模板使用次数
  incrementTemplateUsage(templateId: string) {
    const template = this.templates.find(t => t.id === templateId);
    if (template) {
      template.usageCount++;
      template.updateTime = new Date().toISOString();
    }
  }

  // 添加生成的试卷
  addGeneratedPaper(paper: GeneratedPaper) {
    this.generatedPapers.push(paper);
    return paper;
  }

  // 更新生成的试卷
  updateGeneratedPaper(paperId: string, updates: Partial<GeneratedPaper>) {
    const index = this.generatedPapers.findIndex(p => p.id === paperId);
    if (index !== -1) {
      this.generatedPapers[index] = {
        ...this.generatedPapers[index],
        ...updates,
      };
      return this.generatedPapers[index];
    }
    return null;
  }

  // 根据ID获取生成的试卷
  getGeneratedPaperById(paperId: string): GeneratedPaper | undefined {
    return this.generatedPapers.find(p => p.id === paperId);
  }
}

// 创建全局实例
export const examStore = new ExamStore(); 



